<?php
/*
 * 此文件用于验证短信服务API接口，供开发时参考
 * 执行验证前请确保文件为utf-8编码，并替换相应参数为您自己的信息，并取消相关调用的注释
 * 建议验证前先执行Test.php验证PHP环境
 *
 * 2017/11/30
 */

namespace App\Libs\Dysms;

class Sms {

    private $accessKeyId = "LTAIp3nfpQGdljss";
    private $accessKeySecret = "tqnKQDQyGiK1xrUF0udXimGQknJLPY";
    private $signName = "零买买";
    private $templateCode = "SMS_134090184";

    /**
     * 发送短信
     */
    public function send($mobile, $code) {

        $params = array ();

        $params["PhoneNumbers"] = $mobile;
        $params["SignName"] = $this->signName;
        $params["TemplateCode"] = $this->templateCode;

        $params['TemplateParam'] = Array (
            "code" => $code,
        );

        // 可选: 设置发送短信流水号
        //$params['OutId'] = "12345";
        // 可选: 上行短信扩展码, 扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段
        //$params['SmsUpExtendCode'] = "1234567";

        if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
            $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
        }

        // 初始化SignatureHelper实例用于设置参数，签名以及发送请求
        $helper = new SignatureHelper();

        // 此处可能会抛出异常，注意catch
        $result = $helper->request(
            $this->accessKeyId,
            $this->accessKeySecret,
            "dysmsapi.aliyuncs.com",
            array_merge($params, array(
                "RegionId" => "cn-hangzhou",
                "Action" => "SendSms",
                "Version" => "2017-05-25",
            ))
        // fixme 选填: 启用https
        // ,true
        );

        //print_r($result);die;
        if ($result->Code != 'OK') {
            // todo 报警 记日志

            return false;
        }

        return true;
    }

}
